package com.jsyxdl.k3cloud.listener.handling;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.doc.vo.DocDetails;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.partbom.dto.ChildPartsFiltersDTO;
import com.hustcad.plm.pdm.partbom.dto.PartBomTree;
import com.hustcad.plm.pdm.partbom.dto.PartUsageLink;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartRelObjectService;
import com.hustcad.plm.pdm.partbom.vo.PartBomTreeByFilterVO;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.user.service.TyplmUserService;
import com.jsyxdl.entity.PartUsageLinkDiffResultDTO;
import com.jsyxdl.entity.PurchaseDiffDTO;
import com.jsyxdl.k3cloud.listener.K3CloudHttpService;
import com.jsyxdl.k3cloud.utils.HttpMethodEnum;
import com.jsyxdl.k3cloud.utils.PlmPartOptionUtils;
import com.jsyxdl.k3cloud.utils.SendErpDataUtils;
import com.jsyxdl.service.ErpK3cloudService;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.exception.message.SystemErrorCodeEnum;

import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 采购申请单处理服务
 */
public class ProcurementHandling {


    public JSONObject productionCall(Map<String, Object> executionType, FlowObject flowObject,UserDO userDO) throws Exception {
        PlmPartOptionUtils plmPartOptionUtils = SpringUtil.getBean(PlmPartOptionUtils.class);
        ErpK3cloudService erpK3cloudService = SpringUtil.getBean(ErpK3cloudService.class);
        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
        TyplmPartRelObjectService typlmPartRelObjectService=SpringUtil.getBean(TyplmPartRelObjectService.class);
        BigInteger poid = flowObject.getRefObjectOid();

        String k3cloud = (String) executionType.get("k3cloud");
        String code = (String) executionType.get("code");

        String poType = flowObject.getRefObjectOtype();
        PartDetailsVO parent = plmPartOptionUtils.getPartDetailsVO(poid, poType);
        //查询ERP用户
        TyplmUserService typlmUserService = SpringUtil.getBean(TyplmUserService.class);
        userDO = typlmUserService.queryUserByKey(parent.getCreatoroid());
        String name=userDO.getName();
        if(name.indexOf("(")!= -1){
            name=name.substring(0,name.indexOf("("));
            userDO.setName(name);
        }
        JSONObject userJson=getErpUser(userDO,executionType);
        if(userJson==null){
            k3CloudHttpService.saveLogs(parent.getIdentifierDisplayName(),"","失败", "查询不到ERP用户信息", "", k3cloud, code);
            throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("查询不到ERP用户信息:"+userDO.getName());

        }





        List<Map<String, Object>> options = k3CloudHttpService.getOptions(code, k3cloud);


        JSONObject httpResult = new JSONObject();
        httpResult.put("IsSuccessByAPI", true);


        PurchaseDiffDTO purchaseDiffDTO = new PurchaseDiffDTO();
        purchaseDiffDTO.setId(UUID.randomUUID().toString());
        purchaseDiffDTO.setObjectNumber(parent.getObjectNumber());
        purchaseDiffDTO.setVersion(parent.getVersion());
        purchaseDiffDTO.setIteration(parent.getIteration());


        Map<String, Object> inMap = k3CloudHttpService.getInTreeMap(code, k3cloud);

        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);



        com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
        expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

        ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
        childPartsFiltersDTO.setBaseLineOid("");
        childPartsFiltersDTO.setDate("");
        childPartsFiltersDTO.setExpandCondition("latest");
        childPartsFiltersDTO.setLifecycleStateKey("");
        childPartsFiltersDTO.setPurposeOfBom("");
        childPartsFiltersDTO.setSpareBom("");
        childPartsFiltersDTO.setView(parent.getView());
        List<ChildPartsFiltersDTO> list = new ArrayList<>();
        list.add(childPartsFiltersDTO);
        expandBomTreeByFilterDTO.setConditions(list);

        expandBomTreeByFilterDTO.setExpandLevel("1");
        expandBomTreeByFilterDTO.setFatherNumber(parent.getObjectNumber());
        expandBomTreeByFilterDTO.setFatherOid(String.valueOf(parent.getOid()));
        expandBomTreeByFilterDTO.setFatherOtype(parent.getOtype());
        expandBomTreeByFilterDTO.setFilterMode("0");
        expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
        expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
        expandBomTreeByFilterDTO.setIsApplyRoot(false);
        expandBomTreeByFilterDTO.setIsFilterAttr(false);
        expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
        expandBomTreeByFilterDTO.setIsNestedTree(false);
        expandBomTreeByFilterDTO.setIsQueryIBA(true);

        PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                    Boolean.TRUE);

        List<PartUsageLinkDiffResultDTO> differences = k3CloudHttpService.getErpHistoricalVersion().getPartDiffResults(
                flowObject);
        Map<String, PartUsageLinkDiffResultDTO> differenceMap = new HashMap<>();
        for (int a = 0; a < differences.size(); a++) {
            differenceMap.put(differences.get(a).getObjectNumber(), differences.get(a));
        }

        for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
            PartBomTree partBomTree = result.getPartBomTreeList().get(y);
            if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                if (differenceMap.containsKey(partBomTree.getObjectNumber())==false) {
                    result.getPartBomTreeList().remove(y);
                    y--;
                }
            }
        }

        if(result.getPartBomTreeList().size()<2){
            JSONObject resultObj = new JSONObject();
            resultObj.put("IsSuccess", true);
            resultObj.put("msg", "没有需要采购的物料");
            JSONObject responseStatus = new JSONObject();
            responseStatus.put("ResponseStatus", resultObj);
            httpResult.put("Result", responseStatus);
            k3CloudHttpService.saveLogs(parent.getIdentifierDisplayName(),"","成功", httpResult.toJSONString(), "", k3cloud, code);
            return httpResult;
        }

        Map<String, PartBomTree> cfpartMap = new HashMap<>();
        Map<String, Object> bomKeyValue = new HashMap<>();
        Map<String,String> docDetailsDown=new HashMap<>();

        //取ObjectNumber查询对应的ERP库存
        List<String> objectNumbers = new ArrayList<>();
        //整合相同编码的物料
        for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
            PartBomTree partBomTree = result.getPartBomTreeList().get(y);
            if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                BigInteger oid = partBomTree.getOid();
                String oType = partBomTree.getOtype();
                PartUsageLink partUsageLink = plmPartOptionUtils.getPartUsageLink(oid, oType);
                partBomTree.setAmount(partUsageLink.getAmount());

                if (differenceMap.containsKey(partBomTree.getObjectNumber())) {
                    PartUsageLinkDiffResultDTO partUsageLinkDiffResultDTO = differenceMap.get(
                            partBomTree.getObjectNumber());
                    partBomTree.setAmount(partUsageLinkDiffResultDTO.getAmountDiff());
                }

                //累计相同物料编码的数量
                if (cfpartMap.containsKey(partBomTree.getObjectNumber())) {
                    PartBomTree pbt = cfpartMap.get(partBomTree.getObjectNumber());
                    pbt.setAmount(pbt.getAmount() + partBomTree.getAmount());
                    result.getPartBomTreeList().remove(y);
                    y--;
                } else {
                    objectNumbers.add(partBomTree.getObjectNumber());
                    cfpartMap.put(partBomTree.getObjectNumber(), partBomTree);
                }
            }
        }


        Map<String, Object> erpListMap = new HashMap<>();
        if (objectNumbers.size() > 0) {
            List<JSONObject> erpList = getErpImmediateInventory(objectNumbers, executionType);
            if (erpList != null && erpList.size() > 0) {
                for (int z = 0; z < erpList.size(); z++) {
                    String sFNumber=erpList.get(z).getString("FNumber");
                    double dValue=erpList.get(z).getDoubleValue("FBaseQty");
                    if(erpListMap.containsKey(sFNumber)==false){
                        erpListMap.put(sFNumber, dValue);
                    }
                    else{
                        double mValue= (double) erpListMap.get(sFNumber);
                        erpListMap.put(sFNumber, dValue+mValue);
                    }
                }
            }
        }

        //和库存比较，保存需要出库的物料或采购的物料
        Map<String,Object> outMap=new HashMap<>();
        Map<String,Object> ingMap=new HashMap<>();

        for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
            PartBomTree partBomTree = result.getPartBomTreeList().get(y);
            if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                double cg=partBomTree.getAmount().doubleValue();
                if(erpListMap.containsKey(partBomTree.getObjectNumber())){
                    double kc= (double) erpListMap.get(partBomTree.getObjectNumber());
                    if((kc-cg)>=0){
                        //库存足够
                        outMap.put(partBomTree.getObjectNumber(),partBomTree);
                    }
                    else{
                        //库存不足
                        ingMap.put(partBomTree.getObjectNumber(),partBomTree);
                    }
                }
                else{
                    //没有库存
                    ingMap.put(partBomTree.getObjectNumber(),partBomTree);
                }
            }
        }




        //生成采购单
        if(ingMap.size()>0){
            for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                PartBomTree partBomTree = result.getPartBomTreeList().get(y);
                if (partBomTree.getOid() != BigInteger.valueOf(0L)) {

                    if(ingMap.containsKey(partBomTree.getObjectNumber())==false){
                        continue;
                    }

                    BigInteger partOid = new BigInteger(partBomTree.getPartoid());
                    String partType = partBomTree.getPartotype();
                    PartDetailsVO partDetailsVO = plmPartOptionUtils.getPartDetailsVO(partOid, partType);

                    //父级物料部门属性赋值到子级
                    if (parent != null) {
                        Map<String, List<String>> partMap = partDetailsVO.getIbaAttributeMap();
                        if (partMap == null) {
                            partMap = new HashMap<>();
                        }
                        Map<String, List<String>> parentMap = parent.getIbaAttributeMap();
                        if (parentMap.containsKey("申请部门")) {
                            partMap.put("申请部门", parentMap.get("申请部门"));
                        }
                        if (parentMap.containsKey("项目号")) {
                            partMap.put("项目号", parentMap.get("项目号"));
                        }
                    }

                    JSONObject partJson = JSONObject.parseObject(JSONObject.toJSONString(partDetailsVO));

                    List<Map<String, Object>> baseCodeList = erpK3cloudService.getBaseCode(
                            partDetailsVO.getClassId());
                    if (baseCodeList != null && baseCodeList.size() > 0) {
                        partJson.put("baseClassificationCode", baseCodeList.get(0).get("objectnumber"));
                    }
                    List<DocDetails> docDetailsList=typlmPartRelObjectService.queryPartRelatedDocInfo(new BigInteger(partDetailsVO.getOid()));
                    if(docDetailsList.size()>0){
                        boolean isAdd=false;
                        for(int i=0;i<docDetailsList.size();i++){
                            if("主控".equals(docDetailsList.get(i).getBuildRuleName())){
                                if("DESIGN APPROVED".equals(docDetailsList.get(i).getLifecycleStateKey())
                                        ||"PROTOTYPE".equals(docDetailsList.get(i).getLifecycleStateKey())
                                        ||"TRIALPRODUCTION".equals(docDetailsList.get(i).getLifecycleStateKey())
                                        ||"PRODUCTION".equals(docDetailsList.get(i).getLifecycleStateKey())
                                        ||"RELEASED".equals(docDetailsList.get(i).getLifecycleStateKey())
                                        ||"PRODUCTION_RELEASED".equals(docDetailsList.get(i).getLifecycleStateKey())) {
                                    isAdd=true;
                                    InetAddress ad= Inet4Address.getLocalHost();
                                    JSONObject docJson=new JSONObject();
                                    docJson.put("oid",docDetailsList.get(i).getOid());
                                    docJson.put("oType",docDetailsList.get(i).getCadType());
                                    docJson.put("label",docDetailsList.get(i).getIdentifierDisplayName());

                                    String down="http://"+ad.getHostAddress()+":7002/#/homePage/docData?param=n5gv2XlanY9r0_smm2x00&objOrginalParam=";
                                    down+= URLEncoder.encode(docJson.toJSONString(), "UTF-8");
                                    docDetailsDown.put(partDetailsVO.getObjectNumber(),down);

                                }
                            }
                        }
                        if(isAdd==false){
                            for(int i=0;i<docDetailsList.size();i++){
                                if("主控".equals(docDetailsList.get(i).getBuildRuleName())==false){
                                    if("DESIGN APPROVED".equals(docDetailsList.get(i).getLifecycleStateKey())
                                            ||"PROTOTYPE".equals(docDetailsList.get(i).getLifecycleStateKey())
                                            ||"TRIALPRODUCTION".equals(docDetailsList.get(i).getLifecycleStateKey())
                                            ||"PRODUCTION".equals(docDetailsList.get(i).getLifecycleStateKey())
                                            ||"RELEASED".equals(docDetailsList.get(i).getLifecycleStateKey())
                                            ||"PRODUCTION_RELEASED".equals(docDetailsList.get(i).getLifecycleStateKey())) {
                                        isAdd=true;
                                        InetAddress ad= Inet4Address.getLocalHost();
                                        JSONObject docJson=new JSONObject();
                                        docJson.put("oid",docDetailsList.get(0).getOid());
                                        docJson.put("oType",docDetailsList.get(0).getCadType());
                                        docJson.put("label",docDetailsList.get(0).getIdentifierDisplayName());

                                        String down="http://"+ad.getHostAddress()+":7002/homePage/docData?param=n5gv2XlanY9r0_smm2x00";
                                        down+= URLEncoder.encode(docJson.toJSONString(), "UTF-8");
                                        docDetailsDown.put(partDetailsVO.getObjectNumber(),down);

                                    }
                                }
                            }
                        }
                    }
                    Map<String, Object> partKeyValue = new HashMap<>();
                    for (Map<String, Object> option : options) {
                        if ("类型属性".equals(option.get("plmtype"))) {
                            k3CloudHttpService.setInTree(
                                    (List<Map<String, Object>>) inMap.get(option.get("plm_source_type_id")),
                                    partJson, partKeyValue);
                            break;
                        }
                    }


                    BigInteger oid = partBomTree.getOid();
                    String oType = partBomTree.getOtype();
                    PartUsageLink partUsageLink = plmPartOptionUtils.getPartUsageLink(oid, oType);
                    partUsageLink.setAmount(partBomTree.getAmount());

                    JSONObject voJson = JSONObject.parseObject(JSONObject.toJSONString(partUsageLink));
                    Map<String, Object> voJsonMap = voJson.getInnerMap();

                    String plm_source_type_id = null;
                    Map<String, Object> listKeyValue = new HashMap<>();
                    for (Map<String, Object> option : options) {
                        if ("BOM属性".equals(option.get("plmtype"))) {
                            plm_source_type_id = (String) option.get("plm_source_type_id");
                            k3CloudHttpService.setInTree((List<Map<String, Object>>) inMap.get(plm_source_type_id),
                                                         voJsonMap, listKeyValue);
                            break;
                        }
                    }
                    listKeyValue.putAll(partKeyValue);

                    if (bomKeyValue.containsKey(plm_source_type_id)) {
                        List<Map<String, Object>> bomList = (List<Map<String, Object>>) bomKeyValue.get(
                                plm_source_type_id);
                        bomList.add(listKeyValue);
                    } else {
                        List<Map<String, Object>> bomList = new ArrayList<>();
                        bomList.add(listKeyValue);
                        bomKeyValue.put(plm_source_type_id, bomList);
                    }
                }
                else {

                    BigInteger oid = new BigInteger(partBomTree.getPartoid());
                    String oType = partBomTree.getPartotype() + "|" + partBomTree.getOtype();
                    PartDetailsVO partDetailsVO = plmPartOptionUtils.getPartDetailsVO(oid, oType);

                    JSONObject partJson = JSONObject.parseObject(JSONObject.toJSONString(partDetailsVO));
                    List<Map<String, Object>> baseCodeList = erpK3cloudService.getBaseCode(partDetailsVO.getClassId());
                    if (baseCodeList != null && baseCodeList.size() > 0) {
                        partJson.put("baseClassificationCode", baseCodeList.get(0).get("objectnumber"));
                    }

                    Map<String, Object> partKeyValue = new HashMap<>();
                    for (Map<String, Object> option : options) {
                        if ("类型属性".equals(option.get("plmtype"))) {
                            k3CloudHttpService.setInTree(
                                    (List<Map<String, Object>>) inMap.get(option.get("plm_source_type_id")), partJson,
                                    partKeyValue);
                            break;
                        }
                    }
                    bomKeyValue.putAll(partKeyValue);
                }
            }

            Map<String, Object> out = k3CloudHttpService.plmToK3CloudOut(code, k3cloud, new HashMap<>(), bomKeyValue);

            //用ERP的用户信息值替换出参中的值
            if(out.containsKey("Model")){
                Map<String,Object> Model= (Map<String, Object>) out.get("Model");
                Map<String,Object> FApplicantId= (Map<String, Object>) Model.get("FApplicantId");
                FApplicantId.put("FNumber",userJson.getString("FStaffNumber"));

                Map<String,Object> FApplicationDeptId= (Map<String, Object>) Model.get("FApplicationDeptId");
                FApplicationDeptId.put("FNumber",userJson.getString("PostDept"));

                List<Map<String,Object>> FEntity= (List<Map<String, Object>>) Model.get("FEntity");
                for(int y=0;y<FEntity.size();y++){
                    FEntity.get(y).put("FNUMBER",userJson.getString("PostDept"));
                    Map<String,Object> FMaterialId= (Map<String, Object>) FEntity.get(y).get("FMaterialId");
                    String FNumber= (String) FMaterialId.get("FNumber");
                    if(docDetailsDown.containsKey(FNumber)){
                        //下载链接
                        FEntity.get(y).put("F_SDTD_XZLJ ",docDetailsDown.get(FNumber));
                    }

                    //把当前时间查询到的库存写到ERP，方便检查问题
                    double erpValue=0;
                    if(erpListMap.containsKey(FNumber)){
                        erpValue= (double) erpListMap.get(FNumber);
                    }
                    FEntity.get(y).put("F_SDTD_KCSL ",erpValue);
                }
            }


            executionType.put("plm_code",parent.getIdentifierDisplayName());


            List<String> erpNumbers = new ArrayList<>();
            httpResult = SendErpDataUtils.sendErpDataTaskWorkder(executionType, out);
            JSONObject Result = httpResult.getJSONObject("Result");
            if (Result != null) {
                JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");
                if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                            ResponseStatus.get("Errors").toString());
                }
                else{
                    JSONArray successEntitys = ResponseStatus.getJSONArray("SuccessEntitys");
                    if (successEntitys.size() > 0) {
                        String erpNumber = successEntitys.getJSONObject(0).getString("Number");
                        erpNumbers.add(erpNumber);
                    }
                }
            }

            executionType.put("code","TJ000006X");
            httpResult=SubmissionAndReviewHanding.submitt(executionType,erpNumbers);
        }

        //生成出库单
        if(outMap.size()>0){
            bomKeyValue=new HashMap<>();
            executionType = k3CloudHttpService.getExecutionType("YX00003X", "出库申请单");
            executionType.put("k3cloud","出库申请单");
            executionType.put("code","YX00003X");

            for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                PartBomTree partBomTree = result.getPartBomTreeList().get(y);
                if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                    if(outMap.containsKey(partBomTree.getObjectNumber())==false){
                        continue;
                    }
                    BigInteger partOid = new BigInteger(partBomTree.getPartoid());
                    String partType = partBomTree.getPartotype();
                    PartDetailsVO partDetailsVO = plmPartOptionUtils.getPartDetailsVO(partOid, partType);

                    //父级物料部门属性赋值到子级
                    if (parent != null) {
                        Map<String, List<String>> partMap = partDetailsVO.getIbaAttributeMap();
                        if (partMap == null) {
                            partMap = new HashMap<>();
                        }
                        Map<String, List<String>> parentMap = parent.getIbaAttributeMap();
                        if (parentMap.containsKey("申请部门")) {
                            partMap.put("申请部门", parentMap.get("申请部门"));
                        }
                        if (parentMap.containsKey("项目号")) {
                            partMap.put("项目号", parentMap.get("项目号"));
                        }
                    }

                    JSONObject partJson = JSONObject.parseObject(JSONObject.toJSONString(partDetailsVO));

                    List<Map<String, Object>> baseCodeList = erpK3cloudService.getBaseCode(
                            partDetailsVO.getClassId());
                    if (baseCodeList != null && baseCodeList.size() > 0) {
                        partJson.put("baseClassificationCode", baseCodeList.get(0).get("objectnumber"));
                    }

                    Map<String, Object> partKeyValue = new HashMap<>();
                    for (Map<String, Object> option : options) {
                        if ("类型属性".equals(option.get("plmtype"))) {
                            k3CloudHttpService.setInTree(
                                    (List<Map<String, Object>>) inMap.get(option.get("plm_source_type_id")),
                                    partJson, partKeyValue);
                            break;
                        }
                    }


                    BigInteger oid = partBomTree.getOid();
                    String oType = partBomTree.getOtype();
                    PartUsageLink partUsageLink = plmPartOptionUtils.getPartUsageLink(oid, oType);
                    partUsageLink.setAmount(partBomTree.getAmount());

                    JSONObject voJson = JSONObject.parseObject(JSONObject.toJSONString(partUsageLink));
                    Map<String, Object> voJsonMap = voJson.getInnerMap();

                    String plm_source_type_id = null;
                    Map<String, Object> listKeyValue = new HashMap<>();
                    for (Map<String, Object> option : options) {
                        if ("BOM属性".equals(option.get("plmtype"))) {
                            plm_source_type_id = (String) option.get("plm_source_type_id");
                            k3CloudHttpService.setInTree((List<Map<String, Object>>) inMap.get(plm_source_type_id),
                                                         voJsonMap, listKeyValue);
                            break;
                        }
                    }
                    listKeyValue.putAll(partKeyValue);

                    if (bomKeyValue.containsKey(plm_source_type_id)) {
                        List<Map<String, Object>> bomList = (List<Map<String, Object>>) bomKeyValue.get(
                                plm_source_type_id);
                        bomList.add(listKeyValue);
                    } else {
                        List<Map<String, Object>> bomList = new ArrayList<>();
                        bomList.add(listKeyValue);
                        bomKeyValue.put(plm_source_type_id, bomList);
                    }
                }
                else {

                    BigInteger oid = new BigInteger(partBomTree.getPartoid());
                    String oType = partBomTree.getPartotype() + "|" + partBomTree.getOtype();
                    PartDetailsVO partDetailsVO = plmPartOptionUtils.getPartDetailsVO(oid, oType);

                    JSONObject partJson = JSONObject.parseObject(JSONObject.toJSONString(partDetailsVO));
                    List<Map<String, Object>> baseCodeList = erpK3cloudService.getBaseCode(partDetailsVO.getClassId());
                    if (baseCodeList != null && baseCodeList.size() > 0) {
                        partJson.put("baseClassificationCode", baseCodeList.get(0).get("objectnumber"));
                    }

                    Map<String, Object> partKeyValue = new HashMap<>();
                    for (Map<String, Object> option : options) {
                        if ("类型属性".equals(option.get("plmtype"))) {
                            k3CloudHttpService.setInTree(
                                    (List<Map<String, Object>>) inMap.get(option.get("plm_source_type_id")), partJson,
                                    partKeyValue);
                            break;
                        }
                    }
                    bomKeyValue.putAll(partKeyValue);
                }
            }

            Map<String, Object> out = k3CloudHttpService.plmToK3CloudOut("YX00003X", "出库申请单", new HashMap<>(), bomKeyValue);

            //用ERP的用户信息值替换出参中的值
            if (out.containsKey("Model")) {
                Map<String, Object> Model = (Map<String, Object>) out.get("Model");
                Map<String, Object> F_WKYT_SQR = (Map<String, Object>) Model.get("F_WKYT_SQR");
                if(F_WKYT_SQR==null){
                    F_WKYT_SQR=new HashMap<>();
                    Model.put("F_WKYT_SQR",F_WKYT_SQR);
                }

                F_WKYT_SQR.put("FSTAFFNUMBER", userJson.getString("StaffNumber"));

                Map<String, Object> FDeptId = (Map<String, Object>) Model.get("FDeptId");
                FDeptId.put("FNumber", userJson.getString("PostDept"));

                List<Map<String,Object>> FEntity= (List<Map<String, Object>>) Model.get("FEntity");
                for(int y=0;y<FEntity.size();y++){
                    Map<String,Object> FMaterialId= (Map<String, Object>) FEntity.get(y).get("FMaterialId");
                    String FNumber= (String) FMaterialId.get("FNumber");

                    //把当前时间查询到的库存写到ERP，方便检查问题
                    double erpValue=0;
                    if(erpListMap.containsKey(FNumber)){
                        erpValue= (double) erpListMap.get(FNumber);
                    }
                    FEntity.get(y).put("F_SDTD_KCSL ",erpValue);
                }
            }

            List<String> erpNumbers = new ArrayList<>();

            httpResult = SendErpDataUtils.sendErpDataTaskWorkder(executionType, out);
            JSONObject Result = httpResult.getJSONObject("Result");
            if (Result != null) {
                JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");
                if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                            ResponseStatus.get("Errors").toString());

                }
                else{
                    JSONArray successEntitys = ResponseStatus.getJSONArray("SuccessEntitys");
                    if (successEntitys.size() > 0) {
                        String erpNumber = successEntitys.getJSONObject(0).getString("Number");
                        erpNumbers.add(erpNumber);
                    }
                }
            }

            executionType.put("code","TJ000006X");
            httpResult=SubmissionAndReviewHanding.submitt(executionType,erpNumbers);
        }

        return httpResult;
    }

    /**
     * 读取ERP库存数据
     *
     * @param objectNumbers
     * @return
     * @throws Exception
     */
    public List<JSONObject> getErpImmediateInventory(List<String> objectNumbers, Map<String, Object> executionType)
            throws Exception {
        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
        SendErpDataUtils.init();

        String port = (String) executionType.get("port");
        String home = (String) executionType.get("home");

        JSONObject outMap = new JSONObject();
        outMap.put("FormId", "STK_Inventory");
        outMap.put("TopRowCount", 0);
        outMap.put("StartRow", 0);
        outMap.put("Limit", 99999999);


        JSONArray FilterStringJson = new JSONArray();
        JSONObject FilterStringObject = new JSONObject();
        FilterStringObject.put("FieldName", "FMaterialId.FNumber");
        FilterStringObject.put("Compare", 338);
        FilterStringObject.put("Logic", 0);
        FilterStringObject.put("Left", "");
        FilterStringObject.put("Right", "");
        String number = "";
        for (int i = 0; i < objectNumbers.size(); i++) {
            if (i > 0) {
                number += ",";
            }
            number += objectNumbers.get(i);
        }
        FilterStringObject.put("Value", number);
        FilterStringJson.add(FilterStringObject);


        FilterStringObject = new JSONObject();
        FilterStringObject.put("FieldName", "FStockName");
        FilterStringObject.put("Compare", 34);
        FilterStringObject.put("Logic", 0);
        FilterStringObject.put("Value", "车间");
        FilterStringObject.put("Left", "");
        FilterStringObject.put("Right", "");
        FilterStringJson.add(FilterStringObject);

        FilterStringObject = new JSONObject();
        FilterStringObject.put("FieldName", "FStockName");
        FilterStringObject.put("Compare", 34);
        FilterStringObject.put("Logic", 0);
        FilterStringObject.put("Value", "报废");
        FilterStringObject.put("Left", "");
        FilterStringObject.put("Right", "");
        FilterStringJson.add(FilterStringObject);

        FilterStringObject = new JSONObject();
        FilterStringObject.put("FieldName", "FStockName");
        FilterStringObject.put("Compare", 34);
        FilterStringObject.put("Logic", 0);
        FilterStringObject.put("Value", "不良");
        FilterStringObject.put("Left", "");
        FilterStringObject.put("Right", "");
        FilterStringJson.add(FilterStringObject);

        FilterStringObject = new JSONObject();
        FilterStringObject.put("FieldName", "FStockName");
        FilterStringObject.put("Compare", 34);
        FilterStringObject.put("Logic", 0);
        FilterStringObject.put("Value", "封存");
        FilterStringObject.put("Left", "");
        FilterStringObject.put("Right", "");
        FilterStringJson.add(FilterStringObject);

        FilterStringObject = new JSONObject();
        FilterStringObject.put("FieldName", "FStockName");
        FilterStringObject.put("Compare", 34);
        FilterStringObject.put("Logic", 0);
        FilterStringObject.put("Value", "中转");
        FilterStringObject.put("Left", "");
        FilterStringObject.put("Right", "");
        FilterStringJson.add(FilterStringObject);

        //库存物料编码，库存量(基本单位),库存名称,规格型号，基本单位，库存状态
        String FieldKeys = "FMaterialId.FNumber,FMaterialName,FBaseQty,FModel,FStockUnitId.FName,FStockStatusId.FName";
        outMap.put("FieldKeys", FieldKeys);
        outMap.put("FilterString", FilterStringJson);

        JSONObject httpResult = new JSONObject();
        httpResult.put("IsSuccessByAPI",true);
        if (k3CloudHttpService.getCookieStr() == null) {
            Map<String, Object> login = new HashMap<>();
            login.put("acctID", SendErpDataUtils.acctID);
            login.put("lcid", 2052);
            login.put("username", SendErpDataUtils.username);
            login.put("password", SendErpDataUtils.password);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                        login);
        }
        if (httpResult.getBoolean("IsSuccessByAPI")) {
            Map<String, Object> outParameter = new HashMap<>();
            outParameter.put("formid", "STK_Inventory");
            outParameter.put("data", outMap);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc",
                                                                        outParameter);
            if (httpResult.containsKey("Result")) {
                JSONObject resultObj = httpResult.getJSONObject("Result");
                JSONObject responseStatus = resultObj.getJSONObject("ResponseStatus");
                if (responseStatus.getBooleanValue("IsSuccess") == false) {
                    if (responseStatus.getLongValue("MsgCode") == 1) {
                        k3CloudHttpService.setCookieStr(null);
                        k3CloudHttpService.setKdserviceSessionid(null);

                        Map<String, Object> login = new HashMap<>();
                        login.put("acctID", SendErpDataUtils.acctID);
                        login.put("lcid", 2052);
                        login.put("username", SendErpDataUtils.username);
                        login.put("password", SendErpDataUtils.password);
                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                    home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                                    login);
                        if (httpResult.containsKey("IsSuccess")) {
                            if (httpResult.getBoolean("IsSuccess")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc",
                                                                                            outParameter);
                            }

                        } else if (httpResult.containsKey("IsSuccessByAPI")) {
                            if (httpResult.getBoolean("IsSuccessByAPI")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc",
                                                                                            outParameter);
                            }
                        }
                    }
                }
            }

            List<JSONObject> list = new ArrayList<>();
            if (httpResult != null) {
                if (httpResult.containsKey("Result") == false && httpResult.containsKey("messages")) {
                    JSONArray resultList = httpResult.getJSONArray("messages");
                    for (int i = 0; i < resultList.size(); i++) {
                        JSONArray value = resultList.getJSONArray(i);
                        JSONObject entity = new JSONObject();
                        entity.put("FNumber", value.get(0));
                        entity.put("FMaterialName", value.get(1));
                        entity.put("FBaseQty", value.get(2));
                        entity.put("FModel", value.get(3));
                        entity.put("FStockUnitIdFName", value.get(4));
                        entity.put("FStockStatusIdFName", value.get(5));
                        list.add(entity);
                    }
                    return list;
                }
            }
        }

        return null;
    }
    /**
     * 查询ERP用户信息
     * @param userDO
     * @param executionType
     * @return
     * @throws Exception
     */
    public JSONObject getErpUser(UserDO userDO, Map<String, Object> executionType) throws Exception {
        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
        SendErpDataUtils.init();

        String port = (String) executionType.get("port");
        String home = (String) executionType.get("home");

        JSONObject outMap = new JSONObject();
        outMap.put("CreateOrgId", 0);
        outMap.put("Id", "");
        outMap.put("IsSortBySeq", false);
        outMap.put("Number",userDO.getName());

        //库存物料编码，库存量(基本单位),库存名称,规格型号，基本单位，库存状态

        JSONObject httpResult = new JSONObject();
        httpResult.put("IsSuccessByAPI",true);

        if (k3CloudHttpService.getCookieStr() == null) {
            Map<String, Object> login = new HashMap<>();
            login.put("acctID", SendErpDataUtils.acctID);
            login.put("lcid", 2052);
            login.put("username", SendErpDataUtils.username);
            login.put("password", SendErpDataUtils.password);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                        login);
        }
        if (httpResult.getBoolean("IsSuccessByAPI")) {
            Map<String, Object> outParameter = new HashMap<>();
            outParameter.put("formid", "BD_Empinfo");
            outParameter.put("data", outMap);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud//Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
                                                                        outParameter);
            if (httpResult.containsKey("Result")) {
                JSONObject resultObj = httpResult.getJSONObject("Result");
                JSONObject responseStatus = resultObj.getJSONObject("ResponseStatus");
                if (responseStatus.getBooleanValue("IsSuccess") == false) {
                    if (responseStatus.getLongValue("MsgCode") == 1) {
                        k3CloudHttpService.setCookieStr(null);
                        k3CloudHttpService.setKdserviceSessionid(null);

                        Map<String, Object> login = new HashMap<>();
                        login.put("acctID", SendErpDataUtils.acctID);
                        login.put("lcid", 2052);
                        login.put("username", SendErpDataUtils.username);
                        login.put("password", SendErpDataUtils.password);
                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                    home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                                    login);
                        if (httpResult.containsKey("IsSuccess")) {
                            if (httpResult.getBoolean("IsSuccess")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
                                                                                            outParameter);
                            }

                        } else if (httpResult.containsKey("IsSuccessByAPI")) {
                            if (httpResult.getBoolean("IsSuccessByAPI")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
                                                                                            outParameter);
                            }
                        }
                    }
                }
            }
            if (httpResult != null) {
                JSONObject Result=httpResult.getJSONObject("Result");
                JSONObject ResponseStatus=Result.getJSONObject("ResponseStatus");
                if(ResponseStatus.getBooleanValue("IsSuccess")==true){
                    JSONObject ResultUser=Result.getJSONObject("Result");
                    JSONObject StaffId=ResultUser.getJSONObject("StaffId");
                    JSONArray PostEntity=ResultUser.getJSONArray("PostEntity");
                    if(PostEntity.size()>0){
                        JSONObject PostDept=PostEntity.getJSONObject(0).getJSONObject("PostDept");
                        JSONObject user=new JSONObject();
                        user.put("StaffNumber",StaffId.getString("StaffNumber"));
                        user.put("FStaffNumber",ResultUser.getString("FStaffNumber"));
                        user.put("PostDept",PostDept.getString("Number"));

                        return user;
                    }
                }
            }
        }
        return null;
    }

}
